package net.huashitong.user.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.util.MD5;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import jodd.util.StringUtil;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.filter.TaskRecordFilter;
import net.huashitong.user.databean.BnpUserDatabean;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.entity.Department;
import net.huashitong.user.entity.Role;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.BranchService;
import net.huashitong.user.service.DepartmentService;
import net.huashitong.user.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/userManageSuper")
public class UserManageController extends JsonBaseController {
    @Override
    protected String getView(String s) {
        return "/modules/userManage/" + s;
    }

    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private BranchService branchService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RoleService roleService;



    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        String branch = request.getParameter("branch");
        model.addAttribute("leftType", "用户管理");
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("user", bnpUser);
        model.addAttribute("nodeCount", nodeCount);
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);
        if (StringUtils.isNotBlank(branch)) {
            model.addAttribute("branch", branch);
        } else {
            model.addAttribute("branch", "");
        }
        return getView("query");
    }

    //初始化数据
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute BnpUserFilter filter, HttpServletRequest request, Model model) {
        List<BnpUser> list = bnpUserService.getUserInfoUsePage(filter);
        //根据deptId添加deptName
        list = bnpUserService.dealWithAddDeptName(list);
        return coverJqGrid(filter, list);
    }

    /**
     * 创建用户
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/createUser", method = RequestMethod.GET)
    public String createUser(@ModelAttribute BnpUserFilter filter, Model model) {
        //项目列表中的责任单位
        List<String> branchs = bnpUserService.getBranchInAllUser();
        model.addAttribute("branchs", branchs);
        return getView("createUser");
    }
    /**
     * 创建用户
     **/
    @ResponseBody
    @RequestMapping(value = "/createUser", method = RequestMethod.POST)
    public Message createCompleteInfo(@ModelAttribute BnpUserFilter filter) {
        BnpUser bnpUser = new BnpUser();
        if (ObjectUtils.isBlank(verifyPhoneExist2(filter.getPhone()))) {
            bnpUser.setPhone(filter.getPhone());
            bnpUser.setName(filter.getName());
            bnpUser.setBranch(filter.getBranch());
            bnpUser.setRole(filter.getRole());
            bnpUser.setBranchType(filter.getBranchType());
            String password = filter.getPassword();
            if (password.length() < 8) {
                return coverMessage("201", "密码长度不小于8位");
            } else {
                String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
                if (!password.matches(regex)) {
                    return coverMessage("201", "密码必须大小写数字混合");
                }
            }
            password = MD5.parseMD5(password);
            bnpUser.setPassword(password);
            bnpUserService.save(bnpUser);
            return coverMessage("200", "添加成功");
        } else {
            return coverMessage("201", "添加失败，手机号已存在");
        }
    }

    private BnpUser verifyPhoneExist2(String phone) {
        return bnpUserService.getBnpUserByPhone(phone);
    }

    /**
     * 修改用户界面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/editUser/{id}", method = RequestMethod.GET)
    public String editUser(Model model, @PathVariable String id) {
        BnpUser bnpUser = bnpUserService.getById(id);
        //项目列表中的责任单位
        List<String> branchs = bnpUserService.getBranchInAllUser();
        List<Department> departments = departmentService.query();
        List<Role> roles =  roleService.query();
        model.addAttribute("branchs", branchs);
        model.addAttribute("bnpUser", bnpUser);
        model.addAttribute("departments", departments);
        model.addAttribute("roles", roles);
        //获取用户的单位（正式）
        Department userDept = new Department();
        if(StringUtil.isNotBlank(bnpUser.getDeptId())){
            userDept = departmentService.getById(bnpUser.getDeptId());
        }
        model.addAttribute("userDept", userDept);
        //获取用户的角色（正式）
        Role role = new Role();
        if(StringUtil.isNotBlank(bnpUser.getRoleId())){
            role = roleService.getById(bnpUser.getRoleId());
        }
        model.addAttribute("role", role);
        return getView("editUser");
    }


    @ResponseBody
    @RequestMapping(value = "/editUser", method = RequestMethod.POST)
    public Message editUser(@ModelAttribute BnpUserFilter filter) {
        //原本用户信息
        BnpUser oldBnpUser = bnpUserService.getById(filter.getSysid());
        oldBnpUser.setDeptId(filter.getDeptId());
        oldBnpUser.setRoleId(filter.getRoleId());
        oldBnpUser.setEffectFlag(filter.getEffectFlag());
        boolean flag = bnpUserService.updateUserInAll(filter, oldBnpUser);
        bnpUserService.update(oldBnpUser);
        if (flag) {
            return coverMessage("200");
        } else {
            return coverMessage("201");
        }
    }
}
